﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AgriculturalMachinery.Models;

namespace AgriculturalMachinery.Models
{
    public class AccountRepository : AgriculturalMachinery.Models.IAccountRepository
    {
        private AgriMachineDataContext amdc = new AgriMachineDataContext();

        // 返回所有已注册用户,考虑加入分页
        public IQueryable<Clients> FindAllClients()
        {
            return amdc.Clients;
        }

        public Clients FindUserByEmail(String Email)
        {
            //return from c in amdc.Clients where c.Email == Email select c;   
            return amdc.Clients.SingleOrDefault(c => c.Email.Equals(Email.Trim()));
        }

        public Clients FindUserByID(int id)
        {
            return amdc.Clients.SingleOrDefault(c => c.UserID == id);
        }

        public Clients FindUserByName(string name)
        {
            return amdc.Clients.SingleOrDefault(c => c.UserName.ToString().Trim().Equals(name));
        }

        public void AddUser(Clients client)
        {
            amdc.Clients.InsertOnSubmit(client);
            save();
        }

        public void DeleteUser(int id)
        {
            amdc.Clients.DeleteAllOnSubmit(from i in amdc.Clients
                                               where i.UserID == id
                                               select i);
            save();
        }

        public void save()
        {
            amdc.SubmitChanges();
        }

        public void ChangeAvatar(int id, string Avatar)
        {
            Clients c = FindUserByID(id);
            c.Avatar = Avatar;
            save();
        }
    }
}
